﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using System.Xml.Linq;

namespace Twi.COMMON.WPF
{
    public static class DataGridExtensions
    {
        //获取DataGrid中列绑定的XElement节点名称
        public static List<string> GetBindingElementNameList(DataGrid dataGrid) 
        {
            List<Binding> bindingList = new List<Binding>();
            foreach (DataGridColumn c in dataGrid.Columns.OfType<DataGridColumn>())
            {
                if (c is DataGridTemplateColumn) 
                {
                    var content = (c as DataGridTemplateColumn).CellTemplate.LoadContent();
                    if (content is DatePicker) 
                    {
                        bindingList.Add((content as DatePicker).GetBindingExpression(DatePicker.SelectedDateProperty).ParentBinding);
                    }      
                }
                else if (c is DataGridBoundColumn) 
                {
                    bindingList.Add((c as DataGridBoundColumn).Binding as Binding);
                }
            }
            List<string> elementNameList = new List<string>();
            foreach (var b in bindingList) 
            {
                foreach (var elementName in b.Path.Path.Split(XElementExtensions.SeperatorArray, StringSplitOptions.RemoveEmptyEntries)) 
                {
                    elementNameList.Add(elementName);
                }
            }
            return elementNameList;
        }

        public static XElement[] GetBindingElements(DataGrid dataGrid)
        {
            List<Binding> bindingList = new List<Binding>();
            foreach (DataGridColumn c in dataGrid.Columns.OfType<DataGridColumn>())
            {
                if (c is DataGridTemplateColumn)
                {
                    var content = (c as DataGridTemplateColumn).CellTemplate.LoadContent();
                    if (content is DatePicker)
                    {
                        bindingList.Add((content as DatePicker).GetBindingExpression(DatePicker.SelectedDateProperty).ParentBinding);
                    }
                }
                else if (c is DataGridBoundColumn)
                {
                    bindingList.Add((c as DataGridBoundColumn).Binding as Binding);
                }
            }
            List<XElement> elementList = new List<XElement>();
            foreach (var b in bindingList)
            {
                foreach (var elementName in b.Path.Path.Split(XElementExtensions.SeperatorArray, StringSplitOptions.RemoveEmptyEntries))
                {
                    elementList.Add(new XElement(elementName));
                }
            }
            return elementList.ToArray();
        }
    }
}
